import React, { useState } from 'react';
import { DeviceGraphList } from './conf';
import { DownOutlined, RightOutlined } from '@ant-design/icons';

/**
 * 设备面板组件属性
 */
interface DevicePanelProps {
  /** 拖拽开始回调 */
  onDragStart: (deviceType: string) => void;
  /** 拖拽结束回调 */
  onDragEnd: () => void;
}

/**
 * 设备分类接口
 */
interface DeviceCategory {
  id: string;
  name: string;
  devices: Array<{
    id: string;
    name: string;
    icon: React.ReactNode;
    width: number;
    height: number;
  }>;
}

/**
 * 设备面板组件
 * 提供可拖拽的设备元素，支持分类和折叠
 */
const DevicePanel: React.FC<DevicePanelProps> = ({ onDragStart, onDragEnd }) => {
  // 整个面板的折叠状态
  const [isPanelCollapsed, setIsPanelCollapsed] = useState(false);

  // 分类折叠状态管理
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
    new Set(['background', 'devices'])
  );

  // 基础组件配置
  const backgroundElements = [
    {
      id: 'text',
      name: '文本',
      icon: (
        <div className="w-full h-full flex items-center justify-center">
          <span className="text-xs font-medium">文本</span>
        </div>
      ),
      width: 100,
      height: 30,
    },
    {
      id: 'image',
      name: '图片',
      icon: (
        <div className="w-full h-full flex items-center justify-center text-gray-400 text-xs">
          图片
        </div>
      ),
      width: 200,
      height: 150,
    },
    {
      id: 'connection-line',
      name: '连线',
      icon: (
        <div className="w-full h-full flex items-center justify-center">
          <svg width="40" height="20" viewBox="0 0 40 20" className="text-blue-500">
            <line
              x1="2"
              y1="10"
              x2="38"
              y2="10"
              stroke="currentColor"
              strokeWidth="2"
              markerEnd="url(#arrowhead)"
            />
            <defs>
              <marker
                id="arrowhead"
                markerWidth="10"
                markerHeight="7"
                refX="9"
                refY="3.5"
                orient="auto"
              >
                <polygon points="0 0, 10 3.5, 0 7" fill="currentColor" />
              </marker>
            </defs>
          </svg>
        </div>
      ),
      width: 100,
      height: 20,
    },
  ];

  // 设备分类配置
  const deviceCategories: DeviceCategory[] = [
    {
      id: 'background',
      name: '基础组件',
      devices: backgroundElements,
    },
    {
      id: 'devices',
      name: '设备组件',
      devices: DeviceGraphList.map(device => ({
        id: device.type,
        name: device.name,
        icon: device.icon,
        width: device.width,
        height: device.height,
      })),
    },
  ];

  /**
   * 切换整个面板的折叠状态
   */
  const togglePanel = () => {
    setIsPanelCollapsed(!isPanelCollapsed);
  };

  /**
   * 切换分类展开/折叠状态
   */
  const toggleCategory = (categoryId: string) => {
    const newExpanded = new Set(expandedCategories);
    if (newExpanded.has(categoryId)) {
      newExpanded.delete(categoryId);
    } else {
      newExpanded.add(categoryId);
    }
    setExpandedCategories(newExpanded);
  };

  /**
   * 处理拖拽开始
   * @param e 拖拽事件
   * @param deviceType 设备类型
   */
  const handleDragStart = (e: React.DragEvent, deviceType: string) => {
    e.dataTransfer.setData('deviceType', deviceType);
    onDragStart(deviceType);
  };

  /**
   * 处理拖拽结束
   */
  const handleDragEnd = () => {
    onDragEnd();
  };

  return (
    <div className="h-full flex flex-col bg-gray-50">
      {/* 标题栏 */}
      <div className="p-0.5 border-b border-gray-200 bg-white">
        <div className="flex items-center justify-between">
          <div>
            {!isPanelCollapsed && (
              <p className="text-sm text-gray-500 mt-1">拖拽或点击添加设备到画布</p>
            )}
          </div>
        </div>
      </div>

      {/* 设备分类列表 */}
      {!isPanelCollapsed && (
        <div className="flex-1 overflow-y-auto bg-white">
          {deviceCategories.map(category => (
            <div key={category.id} className="border-b border-gray-200">
              {/* 分类标题 */}
              <div
                className="flex items-center justify-between p-4 bg-white cursor-pointer hover:bg-gray-50 transition-colors"
                onClick={() => toggleCategory(category.id)}
              >
                <span className="font-medium text-gray-700">{category.name}</span>
                {expandedCategories.has(category.id) ? (
                  <DownOutlined className="text-gray-500" />
                ) : (
                  <RightOutlined className="text-gray-500" />
                )}
              </div>

              {/* 设备网格 */}
              {expandedCategories.has(category.id) && (
                <div className="p-4 bg-gray-50">
                  <div className="grid grid-cols-2 gap-3">
                    {category.devices.map(device => (
                      <div
                        key={device.id}
                        className="bg-white border border-gray-200 rounded-lg p-3 cursor-move hover:shadow-md hover:border-blue-300 transition-all duration-200 group"
                        draggable
                        onDragStart={e => handleDragStart(e, device.id)}
                        onDragEnd={handleDragEnd}
                      >
                        {/* 设备图标 */}
                        <div className="w-full h-20 flex items-center justify-center mb-2 bg-gray-1 rounded group-hover:bg-blue-50 transition-colors">
                          <div className="wh-full text-20 flex items-center justify-center">
                            {device.icon}
                          </div>
                        </div>

                        {/* 设备名称 */}
                        <div className="text-center">
                          <div className="text-xs font-medium text-gray-800 truncate">
                            {device.name}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default DevicePanel;
